package evi.com.evi.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import evi.com.evi.R;
import evi.com.evi.activity.GoodsAddActivity;
import evi.com.evi.activity.GoodsChangeActivity;
import evi.com.evi.activity.GoodsManagerActivity;
import evi.com.evi.bean.GoodsManagerBean;
import evi.com.evi.utils.ContentUtils;
import evi.com.evi.utils.JSONUtils;
import evi.com.evi.utils.SPUtil;
import evi.com.evi.utils.ToastUtils;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class GoodsInfoAdapter<T> extends BaseAdapter {

    private Context mContext;
    private List<T> mList;
    private String name;
    private String category;

    private OkHttpClient client;
    private JSONUtils jsonUtils;

    public GoodsInfoAdapter(Context context, List<T> mList, String name, String category) {
        this.mContext = context;
        this.mList = mList;
        this.name = name;
        this.category = category;
        if (this.mList == null) {
            this.mList = new ArrayList<T>();
        }
        client = new OkHttpClient();
        jsonUtils = new JSONUtils();
    }

    @Override
    public int getCount() {
        return mList.size();
    }

    @Override
    public Object getItem(int position) {
        return mList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        if (convertView == null) {
            viewHolder = new ViewHolder();
            convertView = LayoutInflater.from(mContext).inflate(R.layout.item_lv_goods_info, null);

            viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);
            viewHolder.tv_name = (TextView) convertView.findViewById(R.id.tv_name);
            viewHolder.tv_price = (TextView) convertView.findViewById(R.id.tv_price);
            viewHolder.tv_content = (TextView) convertView.findViewById(R.id.tv_content);
            viewHolder.btn_write = (Button) convertView.findViewById(R.id.btn_write);
            viewHolder.btn_sale = (Button) convertView.findViewById(R.id.btn_sale);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        GoodsManagerBean.DataBean.CategoriesBean.ProductsBean bean = (GoodsManagerBean.DataBean.CategoriesBean.ProductsBean) mList.get(position);
//        viewHolder.iv_image.setImageResource(R.drawable.ic_logo);

        if (bean.getState() == 15001) {
            viewHolder.btn_sale.setText("开售中");
            viewHolder.btn_sale.setBackgroundResource(R.drawable.ic_dialog_refuse);
            viewHolder.btn_sale.setTextColor(Color.WHITE);
        } else {
            viewHolder.btn_sale.setText("停售中");
            viewHolder.btn_sale.setBackgroundResource(R.drawable.ic_dialog_sure);
            viewHolder.btn_sale.setTextColor(Color.BLACK);
        }

        Picasso.with(mContext).load(bean.getImageUrl()).into(viewHolder.iv_image);
//        Picasso.with(mContext).load(ContentUtils.base_url + bean.getImageUrl()).into(viewHolder.iv_image);
        viewHolder.tv_name.setText(bean.getName());
        viewHolder.tv_price.setText("￥" + bean.getPrice());
        viewHolder.tv_content.setText(bean.getIntroduction());

        viewHolder.btn_write.setOnClickListener(new OnitemListener(position, mList.get(position)));
        viewHolder.btn_sale.setOnClickListener(new OnitemListener(position, mList.get(position)));

        return convertView;
    }

    class OnitemListener implements OnClickListener {
        private int position;
        private Object obj;
        private GoodsManagerBean.DataBean.CategoriesBean.ProductsBean bean;

        public OnitemListener(int position, Object obj) {
            this.position = position;
            this.obj = obj;
            bean = (GoodsManagerBean.DataBean.CategoriesBean.ProductsBean) obj;
        }

        @Override
        public void onClick(View v) {

            switch (v.getId()) {
                case R.id.btn_write:        //编辑
                    Intent intent = new Intent(mContext, GoodsChangeActivity.class);

                    intent.putExtra("ActType", "编辑商品");
                    intent.putExtra("name", bean.getName());
                    intent.putExtra("price", bean.getPrice() + "");
                    intent.putExtra("introduction", bean.getIntroduction());
                    intent.putExtra("imageUrl", bean.getImageUrl());
//                    intent.putExtra("categoryId", (String) bean.getCategorytId());
                    intent.putExtra("categoryName", name);
                    intent.putExtra("categoryId", category);
                    intent.putExtra("productId", bean.getProductId());

                    ((Activity) mContext).startActivityForResult(intent, 1);
                    break;

                case R.id.btn_sale://开售，停售
                    if (bean.getState() == 15001) {
                        //开售 → 停售
                        changeState("15002", bean.getProductId(), v);
                    } else {
                        //停售 → 开售
                        changeState("15001", bean.getProductId(), v);
                    }
                    break;

                default:
                    break;
            }
        }

        private void changeState(final String state, String productId, final View v) {

            String token = SPUtil.getString(mContext, "token");
            FormBody.Builder builder = new FormBody.Builder();

            RequestBody body = builder
                    .add("state", state)
                    .add("productId", productId)
                    .build();

            Request request = new Request.Builder()
                    .addHeader("token", token)
                    .url(ContentUtils.updateProductStatus_url)
                    .post(body)
                    .build();

            Log.e("TAG", "state= " + state);

            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    toast("服务器忙碌，请稍后再试");
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String jsonData = response.body().string();
                    if (jsonUtils.validate(jsonData)) {
                        JSONObject jsonObject = JSON.parseObject(jsonData);
                        if (jsonObject.getBoolean("success")) {
                            ((Activity) mContext).runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (state.equals("15002")) {
                                        v.setBackgroundResource(R.drawable.ic_dialog_refuse);
                                        ((Button) v).setText("开售中");
                                        ((Button) v).setTextColor(Color.WHITE);
                                        bean.setState(15002);
                                        notifyDataSetChanged();

                                    } else {
                                        v.setBackgroundResource(R.drawable.ic_dialog_sure);
                                        ((Button) v).setText("停售中");
                                        ((Button) v).setTextColor(Color.BLACK);
                                        bean.setState(15001);
                                        notifyDataSetChanged();
                                    }
                                }
                            });
                        } else {

                        }
                    }
                    Log.e("分类", "商品信息联网成功" + jsonData);
                }
            });
        }

        private void toast(final String string) {
            ((Activity) mContext).runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(mContext, string, Toast.LENGTH_SHORT).show();
                }
            });
        }

    }

    class ViewHolder {
        ImageView iv_image;
        TextView tv_name;
        TextView tv_price;
        TextView tv_content;
        Button btn_write;
        Button btn_sale;
    }

}
